﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
namespace YZZ
{
    class TableTemplate
    {
        protected DataTable m_table;
        public TableTemplate(DataTable table)
        { m_table = table; }

        public DataRow FindRowWith(string key, string value)
        {
            if (m_table.Rows.Count == 0)
                return null;
            if (m_table.Columns.IndexOf(key) < 0)
                return null;
            for (int i = 0; i < m_table.Rows.Count; i++)
            {
                if (m_table.Rows[i][key].ToString() == value)
                    return m_table.Rows[i];
            }
            return null;
        }
        public void RefreshTable(DataTable table)
        {
            m_table = table;
        }
        protected void AddCol(string columnName, Type type)
        {
            m_table.Columns.Add(columnName, type);
        }
        protected DataRow NewRow()
        {
            return m_table.NewRow();
        }
        protected void AddRow(DataRow row)
        {
            m_table.Rows.Add(row);
        }
    }

    class TransactionHelper
    {
        private List<string> command_list { get; set; }
        public TransactionHelper()
        {
            command_list = new List<string>();
        }
        public void SendComandInTransaction(string sqlcommand)
        {
            command_list.Add(sqlcommand);
        }
        public bool Go()
        {
            if (command_list == null || command_list.Count == 0)
                return false;
            Logger log = new Logger();
            // 事务成功返回true，事务失败返回false
            bool result = false;
            string SqlConnectionString = Config.Get("DefaultConnection");
            SqlConnection cn = new SqlConnection(SqlConnectionString);
            SqlCommand cmd = new SqlCommand();
            SqlTransaction transaction = null;
            string CurrentCommand = string.Empty;
            try
            {
                // 打开数据库
                if (cn.State == ConnectionState.Closed)
                {
                    cn.Open();
                }

                // 开始事务
                transaction = cn.BeginTransaction();
                cmd.Transaction = transaction;
                cmd.Connection = cn;
                
                foreach (string command in command_list)
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = command;
                    CurrentCommand = command;
                    if (cmd.ExecuteNonQuery() < 0)
                        throw new Exception();
                    log.AppendLine("执行：" + command);
                }

                // 提交事务
                transaction.Commit();
                result = true;
            }
            catch
            {
                log.AppendLine("执行：" + CurrentCommand + "失败");
                result = false;
                // 回滚事务
                transaction.Rollback();
            }
            finally
            {
                // 关闭数据库
                if (cn.State == ConnectionState.Open)
                {
                    cn.Close();
                }
                cn.Dispose();
                cmd.Dispose();
                transaction.Dispose();
                log.Write();
            }
            return result;
        }
    }

    public class Connection
    {
        public static string m_ConnectionString { get; private set; }

        private string m_Record;
        private DataTable ExecuteQuery(string CommandString)
        {
            if (CommandString == null) return new DataTable();
            DataTable ResultTable;
            SqlDataAdapter Adapter = new SqlDataAdapter(CommandString, m_ConnectionString);
            //创建一个dataset接收Adapter申请下来的数据
            DataSet gotData = new DataSet();
            try
            {
                Adapter.Fill(gotData);
                ResultTable = new DataTable();
                ResultTable = gotData.Tables[0].Clone();

                for (int i = 0; i < gotData.Tables[0].Rows.Count; i++)
                {
                    DataRow gotRow = gotData.Tables[0].Rows[i];
                    ResultTable.Rows.Add(gotRow.ItemArray);

                }
            }
            catch
            {
                m_Record += "查询执行失败;\n";
                return new DataTable();
            }

            return ResultTable;
        }


        public Connection(string ConnectionString = "")
        {
            if (string.IsNullOrEmpty(ConnectionString))
                m_ConnectionString = Config.Get("DefaultConnection");
            else
                m_ConnectionString = ConnectionString;
        }
        public void Execute(string CommandString)
        {
            using (SqlConnection connection = new SqlConnection(
               m_ConnectionString))
            {
                SqlCommand command = new SqlCommand(CommandString, connection);
                command.Connection.Open();
                command.ExecuteNonQuery();
            }
        }
        public DataTable Query(string QueryString)
        {
            return ExecuteQuery(QueryString);
        }
        public string GetReport() { return m_Record; }
    }
}